package com.example.myapplication.Fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.example.myapplication.MainActivity
import com.example.myapplication.R
import com.google.gson.Gson
import com.example.myapplication.Model.City
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader

class CityListFragment : Fragment() {

    private lateinit var listView: ListView
    private var cities: List<City> = emptyList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_city_list, container, false)
        listView = view.findViewById(R.id.listView)
        loadCities()
        return view
    }

    private fun loadCities() {
        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
            val str: String? = readFileFromRaw(R.raw.citycode)
            val gson = Gson()
            val CityType = object : TypeToken<List<City>>() {}.type
            var cities:List<City> = gson.fromJson(str,CityType)
            cities = cities.filter { it.city_code!="" }
            withContext(Dispatchers.Main) {
                val adapter = ArrayAdapter<City>(requireContext(), android.R.layout.simple_list_item_1, cities)
                listView.adapter = adapter
                listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                    val cityCode = cities[position].city_code
                    (activity as MainActivity).showWeatherFragment(cityCode)
                }
            }
        }
    }

    private fun readFileFromRaw(rawName: Int): String? {
        return try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            val result = bufReader.useLines { it.joinToString("") }
            result
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }
}